from flask import Flask, render_template
import os
from datetime import datetime
import json
import threading
import time
from temperature_collector import TemperatureCollector

app = Flask(__name__)
app.config['DATA_ROOT'] = '/data/data_temp'

collector = TemperatureCollector(app.config['DATA_ROOT'])

@app.route('/')
def index():
    # 获取所有观测日数据
    days = []
    if os.path.exists(app.config['DATA_ROOT']):
        # 遍历所有日期子目录
        for day in sorted(os.listdir(app.config['DATA_ROOT']), reverse=True):
            day_path = os.path.join(app.config['DATA_ROOT'], day)
            if not os.path.isdir(day_path):
                continue
                
            # 检查是否存在该日期的JSON文件
            temp_file = os.path.join(day_path, f"{day}_temp.json")
            if os.path.exists(temp_file):
                with open(temp_file) as f:
                    data = json.load(f)
                    cameras = len(data)
                    
                    # 计算故障相机
                    faulty_cameras = {}
                    for cam_id, temps in data.items():
                        max_diff = max(abs(t['TEMPSET']-t['TEMPACT']) for t in temps)
                        if max_diff > 5:
                            faulty_cameras[cam_id] = {'max_diff': max_diff}
                    
                    days.append({
                        'date': day,
                        'cameras': cameras,
                        'faulty': len(faulty_cameras),
                        'faulty_cameras': faulty_cameras
                    })
    
    return render_template('index.html', days=days)

@app.route('/day/<date>')
def day_detail(date):
    # 构建新的JSON文件路径
    temp_file = os.path.join(app.config['DATA_ROOT'], date, f"{date}_temp.json")
    if os.path.exists(temp_file):
        with open(temp_file) as f:
            data = json.load(f)
        return render_template('day_detail.html', date=date, cameras=data)
    return "No data found", 404

def start_collector():
    # 启动定时采集任务
    def run_collector():
        while True:
            collector.collect_temperatures()
            time.sleep(600)  # 10分钟
    
    thread = threading.Thread(target=run_collector)
    thread.daemon = True
    thread.start()

if __name__ == '__main__':
    start_collector()
    app.run(host='0.0.0.0', port=5000)